package com.ody.util.code;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerHelper {

    public static String getHtml(String ftlFileDir, String ftlFilename, Object obj) throws Exception {
        StringWriter writer = new StringWriter();
        write(ftlFileDir, ftlFilename, obj, writer);
        writer.flush();
        return writer.toString();
    }
    
    public static void write(String ftlFileDir, String ftlFilename, Object obj, Writer writer) throws Exception {
        Template tpl = getFreemarkerConfig(ftlFileDir).getTemplate(ftlFilename);
        tpl.setOutputEncoding("UTF-8");
        tpl.process(obj, writer);
    }

    private static Configuration getFreemarkerConfig(String templatePath) throws IOException {
        Configuration config = new Configuration(Configuration.VERSION_2_3_23);
        config.setDirectoryForTemplateLoading(new File(templatePath));
        config.setEncoding(Locale.CHINA, "utf-8");
        return config;
    }

}
